package com.aivin.qiniu;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.File;
import java.io.IOException;
import java.net.URL;

public class QiNiuUpLoad
{


    /***
     *   请填写正确的key 和 secret
     */
    /**ACCESS_KEY*/
    private static String ACCESS_KEY = "xxxxxxxxxxxxx";
    /**SECRET_KEY*/
    private static String SECRET_KEY = "xxxxxxxxxxxxx";
    /**文件前缀*/
    private static String beforeName = "blog_";
    /**七牛域名*/
    private static String WWW = "p1at50vl1.bkt.clouddn.com";
    /** 七牛空间名*/
    private JTextPane jTextPane;/**文件上传组件*/
    private static String bucketname = "blogspace";
    public JFrame frame;
    /**七牛认证*/
    private String filePath;
    /**文件路径*/
    private Auth auth;



    public QiNiuUpLoad()
    {
        initialize();
    }


    public String getFileName(String filePath) {
        File mFile = new File(filePath);
        //  会自动删除非法字符
        return mFile.getName().replace("%", "").replace("#", "");
    }

    public String getUpToken()
    {
        return auth.uploadToken(bucketname);
    }


    private void initialize() {

        frame = new JFrame();
        frame.setTitle("图片上传到七牛");
        frame.setBounds(400, 200, 550, 350);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        jTextPane = getPanel();
        frame.getContentPane().add(jTextPane);
    }


    public JTextPane getPanel() {
        final JTextPane fileTarget = new JTextPane();
        fileTarget.setMargin(new Insets(60, 3, 3, 3));

        // 设置文字水平居中显示
        StyledDocument doc = fileTarget.getStyledDocument();
        SimpleAttributeSet center = new SimpleAttributeSet();
        StyleConstants.setAlignment(center, StyleConstants.ALIGN_CENTER);
        doc.setParagraphAttributes(0, doc.getLength(), center, false);
        fileTarget.setEditable(false);
        fileTarget.setText("将文件拖动到此处上传");
        fileTarget.setDragEnabled(true);
        fileTarget.setTransferHandler(new TransferHandler() {
            private static final long serialVersionUID = 1L;

            public boolean importData(JComponent c, Transferable t) {
                try {
                    Object o = t.getTransferData(DataFlavor.javaFileListFlavor);
                    // 此处输出文件/文件夹的名字以及路径
                    filePath = o.toString().substring(1, o.toString().length() - 1);

                    auth = Auth.create(ACCESS_KEY, SECRET_KEY);
                    fileTarget.setDragEnabled(false);

                    new Thread(new Runnable() {
                        public void run() {
                            Response res;
                            try {
                                // 调用put方法上传
                                if (auth != null) {
                                    String formTime = Tools.getCurrentDataStr() + "_";
                                    fileTarget.setText("上传中...\n\n请等待上传完成后再进行操作");
                                    Configuration cfg = new Configuration(Zone.zone2());//华南区域
                                    res = new UploadManager(cfg).put(filePath, formTime + "" + beforeName + getFileName(filePath), getUpToken());
                                    String json = res.bodyString();
                                    Result result = new Gson().fromJson(json, Result.class);
                                    String fileName;
                                    if (result.getKey().contains("\\")) {
                                        fileName = result.getKey().replace("\\", "\\\\");
                                    } else {
                                        fileName = result.getKey();
                                    }
                                    String lastPath = "http://" + WWW + "/" + fileName;
                                    fileTarget.setText(lastPath + "\n\n" + "链接已经复制到剪贴板\n\n拖动文件到此处继续上传");

                                    // 存储到剪贴板
                                    StringSelection stsel = new StringSelection(lastPath);
                                    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stsel, stsel);
                                    fileTarget.setDragEnabled(true);
                                } else {
                                    JOptionPane.showMessageDialog(frame,  "授权认证失败，请确保信息正确");
                                }
                            } catch (QiniuException e) {
                                fileTarget.setText("上传失败="+e.getMessage());
                            }

                        }
                    }).start();
                    return true;
                }  catch ( Exception e) {
                    fileTarget.setText("发生异常="+e.getMessage());
                }
                return false;
            }

            public boolean canImport(JComponent c, DataFlavor[] flavors)
            {
                return true;
            }
        });
        return fileTarget;
    }


}
